<?php

require_once( dirname( __FILE__ ).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'class.phpmailer.php' );
 
class SmtpMailer extends Mailer
{
    var $mailer = null;
    
    protected $CharSet = "utf-8";   
    protected $SMTPSecure = "ssl";
    protected $SMTPAuth = "true";
    protected $SMTPDebug = "0";
    protected $SetLanguage = "en";
    
    
	function __construct( $mailer = null )
	{
	    parent::__construct();
            $this->mailer = $mailer;
	}


    protected function instanciate()
    {
        $MailConfig = SiteConfig::current_site_config();
        if( null == $this->mailer ) {
	        $this->mailer = new PHPMailer( true );
            $this->mailer->IsSMTP();
            $this->mailer->CharSet = $this->CharSet ? $this->CharSet : "utf-8";
            $this->mailer->Host = $MailConfig->Host ? $MailConfig->Host : "localhost";
            $this->mailer->Port = $MailConfig->Port ? $MailConfig->Port : 25;
            $this->mailer->SMTPSecure = $MailConfig->UseSSL ? strtolower( $this->SMTPSecure ) : '';            
            $this->mailer->SMTPAuth = $this->SMTPAuth ? $this->SMTPAuth : false;
            if( $this->mailer->SMTPAuth ) {
                $this->mailer->Username = $MailConfig->Username ? $MailConfig->Username : "username";
                $this->mailer->Password = $MailConfig->Password ? $MailConfig->Password : "password";
            }
            $this->mailer->SMTPDebug = $this->SMTPDebug ? $this->SMTPDebug : 0;
            $this->mailer->SetLanguage( $this->SetLanguage ? $this->SetLanguage : 'en' );
            
        }
    }	
	

    /* Overwriting Mailer's function */
	function sendPlain($to, $from, $subject, $plainContent, $attachedFiles = false, $customheaders = false)
	{
            $MailConfig = SiteConfig::current_site_config();
            if($MailConfig->UseSMTP)
            {
                $this->instanciate();
                $this->mailer->IsHTML( false );
                $this->mailer->Body = $plainContent;
                return $this->sendMailViaSmtp( $to, $from, $subject, $attachedFiles, $customheaders, false );
            }
            else
                return plaintextEmail($to, $from, $subject, $plainContent, $attachedFiles, $customheaders);
	}


    /* Overwriting Mailer's function */
	function sendHTML($to, $from, $subject, $htmlContent, $attachedFiles = false, $customheaders = false, $plainContent = false, $inlineImages = false)
	{
            $MailConfig = SiteConfig::current_site_config();
			 if(empty($from))
            	$from = $MailConfig->AdminEmail ? $MailConfig->AdminEmail : 'noReply@dragonholding.nl';
            if($MailConfig->UseSMTP)
            {
                $this->instanciate();
                $this->mailer->IsHTML( true );
                if( $inlineImages ) {
                    $this->mailer->MsgHTML( $htmlContent, Director::baseFolder() );
                }
                else {
                    $this->mailer->Body = $htmlContent;
                    if( empty( $plainContent ) ) $plainContent = trim( Convert::html2raw( $htmlContent ) );
                    $this->mailer->AltBody = $plainContent;
                }
                $this->sendMailViaSmtp( $to, $from, $subject, $attachedFiles, $customheaders, $inlineImages );
            }
            else
                return htmlEmail($to, $from, $subject, $htmlContent, $attachedFiles, $customheaders, $plainContent, $inlineImages);
    }
    
    
    protected function sendMailViaSmtp( $to, $from, $subject, $attachedFiles = false, $customheaders = false, $inlineImages = false )
    {
        if( $this->mailer->SMTPDebug > 0 ) echo "<em><strong>*** Debug mode is on</strong>, printing debug messages and not redirecting to the website:</em><br />";
        $msgForLog = "\n*** The sender was : $from\n*** The message was :\n{$this->mailer->AltBody}\n";

        try {
        	$customheaders['MIME-Versionhehe'] = '1.0';
        	
            $this->buildBasicMail( $to, $from, $subject );    
            $this->addCustomHeaders( $customheaders );
            $this->attachFiles( $attachedFiles );
            $this->mailer->Send();

            if( $this->mailer->SMTPDebug > 0 ) {
                echo "<em><strong>*** E-mail to $to has been sent.</strong></em><br />";
                echo "<em><strong>*** The debug mode blocked the process</strong> to avoid the url redirection. So the CC e-mail is not sent.</em>";
                die();
            }

        } catch( phpmailerException $e ) {
            $this->handleError( $e->errorMessage() );
        } catch( Exception $e ) {
            $this->handleError( $e->getMessage() );
        }
    }
    
    
    function handleError( $msg )
    {
        echo $msg;
        Debug::log( $msg );
        die();
    }
        
    protected function buildBasicMail( $to, $from, $subject )
    {
        $mailconfig = SiteConfig::current_site_config();
        if( preg_match('/(\'|")(.*?)\1[ ]+<[ ]*(.*?)[ ]*>/', $from, $from_splitted ) ) {
            // If $from countain a name, e.g. "My Name" <me@acme.com>            
            $this->mailer->SetFrom( $from_splitted[3], $mailconfig->FromName );
        }
        else {
            $this->mailer->SetFrom( $from, $mailconfig->FromName );
        }

        $to = validEmailAddr( $to );
        $this->mailer->ClearAddresses();
        $this->mailer->AddAddress( $to, ucfirst( substr( $to, 0, strpos( $to, '@' ) ) ) ); // For the recipient's name, the string before the @ from the e-mail address is used
        $this->mailer->Subject = $subject;
    }
    
    
    protected function addCustomHeaders( $headers )
    {
    	if( null == $headers or !is_array( $headers ) ) $headers = array();
	    if( !isset( $headers["X-Mailer"] ) ) $headers["X-Mailer"] = X_MAILER;
	    if( !isset( $headers["X-Priority"] ) ) $headers["X-Priority"] = 3;
	
	    $this->mailer->ClearCustomHeaders();
	    foreach( $headers as $header_name => $header_value ) {
	        $this->mailer->AddCustomHeader( $header_name.':'.$header_value );    
	    }
    }
    

    protected function attachFiles( $attachedFiles )
    {
        if( !empty( $attachedFiles ) and is_array( $attachedFiles ) ) {
            foreach( $attachedFiles as $attachedFile ) {
                $this->mailer->AddAttachment( Director::baseFolder().DIRECTORY_SEPARATOR.$attachedFile['filename'] );
            }
        }
    }

}

?>
